import { useTableScroll } from '@/hooks/useTableScroll';
import {
  closeItem,
  getChangeItemData,
  getDetailList,
  getSingleAccountList,
  searchSafePayBatch,
} from '@/services/production-center';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { useSearchParams } from '@umijs/max';
import {
  Button,
  Form,
  FormInstance,
  Input,
  Modal,
  Popconfirm,
  Radio,
  Select,
  message,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import ConfirmModal from '../acs-change/components/ConfirmModal';

const statusOptions = [
  {
    label: '不限',
    value: '',
  },
  {
    label: '待转账',
    value: 'WAIT_ENSURE',
  },
  {
    label: '转账处理中',
    value: 'WAIT_TRANS',
  },

  {
    label: '银行处理中',
    value: 'DEALING',
  },
  {
    label: '全部处理成功',
    value: 'SUCCESS',
  },
  {
    label: '部分处理成功',
    value: 'PART_SUCCESS',
  },
  {
    label: '全部处理成功+部分处理成功',
    value: 'SUCCESS_AND_PART_SUCCESS',
  },
  {
    label: '全部处理失败',
    value: 'FAIL',
  },
  {
    label: '批次废弃',
    value: 'DISUSE',
  },
];

const statusOptionsEnum = statusOptions.reduce((pre, current) => {
  pre[current.value] = {
    text: current.label,
  };
  return pre;
}, {} as any);

const ACSRecord = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [alipayAccountList, setAlipayAccountList] = useState([]);
  const [viewBatchDetail, setViewBatchDetail] = useState<any>(undefined);
  const [viewDetail, setViewDetail] = useState<any>(undefined);
  const modalActionRef = useRef<ActionType>();
  const [modalTableParams, setModalTableParams] = useState({
    status: '',
  });
  const [mainTableParams, setMainTableParams] = useState<any>({});
  const [changeItem, setChangeItem] = useState<any>(undefined);
  const [changeResData, setChangeResData] = useState<any>(undefined);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    formRef.current?.setFieldValue(
      'importBatchNo',
      searchParams.get('importBatchNo'),
    );
  }, [searchParams.get('importBatchNo')]);

  useEffect(() => {
    getSingleAccountList({
      signStatus: 'NORMAL',
    }).then((res: any) => {
      if (res.success) {
        if (res.data?.length) {
          setAlipayAccountList(
            res.data.map((item: any) => ({
              label: item.alipayNickName,
              value: item.alipayNickName,
            })),
          );
        }
      } else {
        message.error(res.resultMessage);
      }
    });
  }, []);

  useEffect(() => {
    if (viewBatchDetail) {
      console.log(123);
      form.setFieldsValue(viewBatchDetail);
    }
  }, [viewBatchDetail]);

  const columns: ProColumns<any>[] = [
    {
      title: '批次创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      width: 180,
      order: 1,
      search: {
        transform: (value: any) => {
          if (!value) return null;
          return {
            minCreateTime: value[0],
            maxCreateTime: value[1],
          };
        },
      },

      render: (_, records) => {
        return <div>{records.createTime}</div>;
      },
    },
    {
      title: '外部批次号',
      dataIndex: 'importBatchNo',
      ellipsis: true,
      width: 180,
      order: 2,
    },
    {
      title: '支付宝账号',
      dataIndex: 'alipayNickName',
      valueType: 'select',
      renderFormItem: () => {
        return <Select options={alipayAccountList}></Select>;
      },
      order: 3,
      ellipsis: true,
      width: 180,
    },
    {
      title: '转账状态',
      dataIndex: 'status',
      width: 160,
      order: 4,
      valueType: 'select',

      render: (_, record) => {
        return (
          <div className={`${record.status === 'DISUSE' ? 'text-[red]' : ''}`}>
            {statusOptionsEnum[record.status].text}
          </div>
        );
      },
      renderFormItem: () => {
        return <Select defaultValue={''} options={statusOptions}></Select>;
      },
    },
    {
      title: '完成时间',
      dataIndex: 'endTime',
      width: 180,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 500,
      fixed: 'right',
      render: (_, record) => [
        <span
          key={'viewBatchDetail'}
          className="cursor-pointer text-[#40a9ff] min-w-fit"
          onClick={() => {
            setViewBatchDetail(record);
          }}
        >
          查看批次详情
        </span>,
        <span
          key={'viewDetail'}
          className="cursor-pointer text-[#40a9ff] min-w-fit"
          onClick={() => {
            setViewDetail(record);
          }}
        >
          查看明细
        </span>,
        <span
          key={'downloaded'}
          className={`cursor-pointer text-[#40a9ff] min-w-fit ${
            dayjs(record.fileExpired).isBefore(dayjs()) ? 'hidden' : ''
          }`}
          onClick={() => {
            window.open(record.fileUrl);
          }}
        >
          下载原文件
        </span>,
        <span
          key={'export'}
          className="cursor-pointer text-[#40a9ff] min-w-fit"
          onClick={() => {
            const formDom = document.createElement('form');
            formDom.setAttribute('type', 'hidden');
            formDom.setAttribute('target', '_black');
            formDom.setAttribute('method', 'get');
            formDom.setAttribute(
              'action',
              '/api/merchant/safe-pay-order/export',
            );

            const inputDom = document.createElement('input');
            inputDom.setAttribute('name', 'batchId');
            inputDom.setAttribute('value', record.id);
            formDom.append(inputDom);
            document.body.append(formDom);
            formDom.submit();
          }}
        >
          导出打款结果明细
        </span>,
        <span
          key={'toChange'}
          className={`cursor-pointer  min-w-fit ${
            record.status !== 'WAIT_ENSURE' ? 'hidden' : ''
          } ${
            loading && changeItem.id === record.id
              ? 'text-[#ccc]'
              : 'text-[#40a9ff]'
          }`}
          onClick={async () => {
            if (loading) return;
            setLoading(true);
            setChangeItem(record);
            try {
              const res = (await getChangeItemData({ id: record.id })) as any;
              if (res.success) {
                setChangeResData(res.data);
              } else {
                message.error(res.resultMessage);
              }
            } catch (error) {
            } finally {
              setLoading(false);
            }
          }}
        >
          发起转账
        </span>,
        <Popconfirm
          key={'close'}
          title="确定关闭吗？"
          trigger={['click']}
          onConfirm={async () => {
            const res = (await closeItem(record.id)) as any;
            if (res.success) {
              message.success('关闭成功！批次服务费已退还到您的系统账户');
              actionRef.current?.reload();
            } else {
              message.error(res.resultMessage);
            }
          }}
        >
          <span
            className={`cursor-pointer text-[#40a9ff] min-w-fit ${
              record.status !== 'WAIT_ENSURE' ? 'hidden' : ''
            }`}
          >
            关闭批次
          </span>
        </Popconfirm>,
      ],
    },
  ];
  const [count, setCount] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);

  return (
    <div>
      <ProTable<any>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        formRef={formRef}
        request={async (params: any) => {
          console.log(params);
          const { data, count } = (await searchSafePayBatch({
            pageNo: params.current - 1,
            pageSize: params.pageSize,
            importBatchNo:
              params.importBatchNo || searchParams.get('importBatchNo'),
            status: params.status,
            alipayNickName: params.alipayNickName,
          })) as any;
          setCount(count + 1);
          setMainTableParams(params);
          return {
            data: data || [],
            total: count,
            success: true,
          };
        }}
        scroll={{ y: tableScrollHeight, x: 200 }}
        columnsState={{
          // persistenceKey: 'merchantList',
          // persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          // onChange(value) {
          //   console.log('value: ', value);
          // },
        }}
        onReset={() => {
          setSearchParams({});
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          defaultPageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        dateFormatter="YYYY-MM-DD 00:00:00"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              const formDom = document.createElement('form');
              formDom.setAttribute('type', 'hidden');
              formDom.setAttribute('target', '_black');
              formDom.setAttribute('method', 'get');
              formDom.setAttribute('action', '/api/merchant/safe-pay/export');
              const inputDom = document.createElement('input');
              inputDom.setAttribute('type', 'hidden');
              inputDom.setAttribute('name', 'searchModelJson');
              const jsonData: any = {
                pageSize: mainTableParams.pageSize,
                pageNo: mainTableParams.current,
                count: mainTableParams.count,
                importBatchNo: mainTableParams.importBatchNo,
                maxCreateTime: mainTableParams.maxCreateTime,
                minCreateTime: mainTableParams.minCreateTime,
              };
              if (mainTableParams.status === 'SUCCESS_AND_PART_SUCCESS') {
                jsonData.statusList = ['SUCCESS', 'PART_SUCCESS'];
                jsonData.status = '';
              } else {
                jsonData.statusList = null;
              }
              inputDom.setAttribute('value', JSON.stringify(jsonData));

              formDom.append(inputDom);
              document.body.append(formDom);
              formDom.submit();
            }}
          >
            导出
          </Button>,
        ]}
      />
      <Modal
        title="提示"
        open={!!viewBatchDetail}
        onCancel={() => {
          setViewBatchDetail(undefined);
        }}
      >
        <div className="flex flex-col gap-6">
          <div>
            系统批次号：<span>{viewBatchDetail?.id}</span>
          </div>
          <div>
            批次总笔数：<span>{viewBatchDetail?.totalCount}</span>
          </div>
          <div>
            成功笔数：<span>{viewBatchDetail?.successCount}</span>
          </div>
          <div>
            失败笔数：<span>{viewBatchDetail?.failCount}</span>
          </div>
          <div>
            批次总金额：<span>{viewBatchDetail?.totalTransAmount}</span>
          </div>
          <div>
            成功金额：<span>{viewBatchDetail?.successAmount}</span>
          </div>
          <div>
            失败金额：<span>{viewBatchDetail?.failedAmount}</span>
          </div>
          <div>
            服务费：<span>{viewBatchDetail?.servicePrice}</span>
          </div>
        </div>
      </Modal>
      {/* 查看明细 */}
      <Modal
        open={!!viewDetail}
        width={1400}
        onCancel={() => {
          setViewDetail(undefined);
        }}
        destroyOnClose
        maskClosable={false}
      >
        <Form
          layout="inline"
          onFinish={(values) => {
            setModalTableParams(values);
            modalActionRef.current?.reload();
          }}
          style={{ paddingLeft: 16, marginTop: 16 }}
        >
          <Form.Item label="转账状态" name={'status'} initialValue={''}>
            <Radio.Group buttonStyle="solid">
              <Radio.Button value="">不限</Radio.Button>
              <Radio.Button value={'WAIT_ENSURE'}>待转账</Radio.Button>
              <Radio.Button value={'WAIT_TRANS'}>转账处理中</Radio.Button>
              <Radio.Button value={'DEALING'}>银行处理中</Radio.Button>
              <Radio.Button value={'SUCCESS'}>成功</Radio.Button>
              <Radio.Button value={'FAIL'}>失败</Radio.Button>
              <Radio.Button value={'DISUSE'}>废弃</Radio.Button>
              <Radio.Button value={'REFUND'}>退票</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="订单编号" name={'importBizNo'}>
            <Input placeholder="订单编号" />
          </Form.Item>
          <Form.Item label="收款账号" name={'identity'}>
            <Input placeholder="收款账号" />
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary">
              查询
            </Button>
          </Form.Item>
        </Form>
        <ProTable
          columns={[
            {
              title: '订单编号',
              dataIndex: 'importBizNo',
              hideInSearch: true,
            },
            {
              title: '支付宝订单号',
              dataIndex: 'payFundOrderId',
              hideInSearch: true,
            },
            {
              title: '收款账号',
              dataIndex: 'identity',
              hideInSearch: true,
            },
            {
              title: '姓名',
              dataIndex: 'name',
              hideInSearch: true,
            },
            {
              title: '金额',
              dataIndex: 'transAmount',
              hideInSearch: true,
            },
            {
              title: '状态',
              dataIndex: 'status',
              hideInSearch: true,
              render: (_, record) => {
                return (
                  <div
                    className={`${
                      record.status === 'DISUSE' ? 'text-[red]' : ''
                    }`}
                  >
                    {statusOptionsEnum[record.status].text}
                  </div>
                );
              },
            },
            {
              title: '失败原因',
              dataIndex: 'errorMsg',
              hideInSearch: true,
            },
            {
              title: '备注',
              dataIndex: 'remark',
              hideInSearch: true,
            },
          ]}
          request={async (params: any) => {
            const res = await getDetailList({
              batchId: viewDetail.id,
              pageNo: params.current - 1,
              pageSize: params.pageSize,
              ...modalTableParams,
            });
            console.log(res);
            return {
              data: res.data || [],
              total: (res as any).count,
              success: true,
            };
          }}
          rowKey="id"
          pagination={{
            defaultPageSize: 10,
          }}
          search={false}
          actionRef={modalActionRef}
        />
      </Modal>
      <ConfirmModal
        title="请核对金额和笔数"
        currentAliPayName={changeItem?.alipayNickName}
        changeResData={changeResData}
        onCancel={(isSuccess) => {
          setChangeResData(undefined);
          if (isSuccess) {
            actionRef.current?.reload();
          }
        }}
      />
    </div>
  );
};

export default ACSRecord;
